<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use App\Http\Service\UserInstance;

class UserController extends Controller
{
    public function login(Request $request)
    {
        $params = $request->all();
        if (!isset($params['name']) || $params['name'] == '') {
            return $this->failed("name不能为空");
        }

        if (!isset($params['password']) || $params['password'] == '') {
            return $this->failed("password不能为空");
        }

        $user = User::where(['name' => $params['name']])->first();

        if (!Hash::check($params['password'], $user->password)) {
            return $this->failed("密码错误");
        }

        $user->api_token = Str::random(64);

        $user->save();

        return $this->success("登录成功", ['api_token' => $user->api_token]);
    }

    public function signup(Request $request)
    {
        $params = $request->all();
        if (!isset($params['name']) || $params['name'] == '') {
            return $this->failed("name不能为空");
        }

        if (!isset($params['password']) || $params['password'] == '') {
            return $this->failed("password不能为空");
        }

        $user = new User();

        $user->name = $params['name'];

        $user->password = Hash::make($params['password']);

        if (isset($params['mobile']) && $params['mobile'] != '') {
            $user->mobile = $params['mobile'];
        }

        $user->save();

        return $this->success("注册成功", $user);
    }

    public function info()
    {
        $user = UserInstance::getInstance()->get();

        return $this->success("成功", $user);
    }
}
